<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="证书编号" prop="certNo">
        <el-input v-model="queryParams.certNo" placeholder="请输入证书编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="学员姓名" prop="certNo">
        <el-input v-model="queryParams.userName" placeholder="请输入学员姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <!-- 规范后的年份选择器 -->
      <el-form-item label="颁发日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="year" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy" placeholder="请选择年份" :clearable="false" :editable="false"
          style="width: 200px">
          <template #prefix>
            <i class="el-icon-date"></i>
          </template>
        </el-date-picker>
      </el-form-item>

      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择">
          <el-option v-for="item in training_classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['cert:cert:add']">颁证</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['cert:cert:export']">导出</el-button>
      </el-col>
      <el-tag class="fr" type="warning">查询统计：{{total}} 人</el-tag>
    </el-row>

    <el-table v-loading="loading" :data="certList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->

      <el-table-column label="证书编号" align="center" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="certNodeatil(scope.row.id)" v-hasPermi="['cert:cert:edit']">{{ scope.row.certNo }}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="证书名称" align="center" prop="name"></el-table-column>
      <el-table-column label="颁发日期" align="center" prop="issuanceDate" width="180">
        <template slot-scope="scope">
          {{parseTime(scope.row.issuanceDate, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column label="颁证机构" align="center" prop="certOrganization.name"></el-table-column>
      <el-table-column label="班级" align="center" prop="trainingClass.name"></el-table-column>
      <el-table-column label="持证人" align="center" prop="student.nickName"></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{scope.row.status==0 ? '申请' : scope.row.status==1 ? '认证' : '注销'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status==1" size="mini" type="text" icon="el-icon-error" @click="cancellatiOpen(scope.row)" v-hasPermi="['cert:cert:edit']">注销</el-button>
          <el-button v-if="scope.row.status==0" size="mini" type="text" icon="el-icon-success" @click="approvalOpen(scope.row)" v-hasPermi="['cert:cert:edit']">认证</el-button>
          <el-button v-if="scope.row.status==0" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['cert:cert:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="660px" append-to-body center :destroy-on-close="true" :before-close="cancel">
      <el-steps :active="active" finish-status="success" style="margin-bottom: 20px;">
        <el-step title="选择班级"></el-step>
        <el-step title="选择机构"></el-step>
        <el-step title="选择人员"></el-step>
        <el-step title="完成颁证"></el-step>
      </el-steps>
      <el-form ref="forms" :model="forms" :rules="rules" label-width="400px">
        <el-form v-if="active == 0">
          <el-row>
            <el-form-item label="班级" prop="classId">
              <el-select @change="getStuList" v-model="forms.classId" placeholder="请选择">
                <el-option v-for="item in training_classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <el-form v-if="active == 1">
          <el-row>
            <el-form-item label="颁证机构" prop="certOrganizationId">
              <el-select v-model="forms.certOrganizationId" placeholder="请选择">
                <el-option v-for="item in cert_organizationList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="颁证类型" prop="certTypeId">
              <el-select v-model="forms.certTypeId" placeholder="请选择">
                <el-option v-for="item in cert_TypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="颁发日期" prop="issuanceDate">
              <el-date-picker clearable v-model="forms.issuanceDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择颁发日期">
              </el-date-picker>
            </el-form-item>
          </el-row>
        </el-form>
        <el-form v-if="active == 2">
          <el-row>
            <div class="el-upload__tip">无法选中为没有头像</div>
            <el-transfer filterable :filter-method="filterMethod"
                         filter-placeholder="请输入姓名" :titles="['未选择','已选择']" v-model="forms.studentIds" :data="studentList"></el-transfer>
          </el-row>
        </el-form>
        <el-form v-if="active == 3">
          <el-descriptions class="margin-top" :column="1" :colon="false">
            <el-descriptions-item>
              <template slot="label"><i class="el-icon-user"></i>&nbsp;颁发学员人数</template>
              {{ forms.studentIds.length }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label"><i class="el-icon-office-building"></i>&nbsp;颁发机构</template>
              {{ forms.name }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label"><i class="el-icon-date"></i>&nbsp;办证日期</template>
              {{ forms.issuanceDate }}
            </el-descriptions-item>
            <el-descriptions-item label="点击“提交”按钮完成办证"></el-descriptions-item>
          </el-descriptions>
        </el-form>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="back" icon="el-icon-arrow-left" type="primary" plain>上一步</el-button>
        <el-button v-if="active<3" style="margin-top: 12px;" @click="next" type="primary" plain>下一步<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        <el-button v-if="active==3" style="margin-top: 12px;" @click="submitForms">提交</el-button>
      </div>
    </el-dialog>


    <!-- 注销证书对话框 -->
    <el-dialog :title="title" :visible.sync="cancellati" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="83px">
        <el-form-item label="注销原因" prop="revocationInfo">
          <el-input v-model="form.revocationInfo" placeholder="请输入注销原因"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 认证证书对话框 -->
    <el-dialog :title="title" :visible.sync="approval" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="83px">
        <el-form-item label="认证说明" prop="approvalInfo">
          <el-input v-model="form.approvalInfo" placeholder="请输入认证说明"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 证书信息对话框 -->
    <el-dialog :title="title" :visible.sync="dialogTableVisible" width="700px">
      <el-tabs v-model="active3" @tab-click="handleClick">
        <el-tab-pane label="证书信息" name="first">
          <div style="width: 100%">
            <div style="width: 50%;float: left">
              <el-descriptions title="证书编号" :column="1">
                <el-descriptions-item label="证书编号">{{ form.certNo }}</el-descriptions-item>
                <el-descriptions-item label="颁发日期">{{ form.issuanceDate }}</el-descriptions-item>
                <el-descriptions-item label="证书名称">{{ form.name }}</el-descriptions-item>
                <el-descriptions-item label="有效期至">{{ form.exp }}</el-descriptions-item>
                <el-descriptions-item label="颁发机构">{{ form.certOrganization.name }}</el-descriptions-item>
                <el-descriptions-item label="持证人员">{{ form.student.nickName }}</el-descriptions-item>
                <el-descriptions-item label="证书状态">
                  <el-tag v-if="form.status==0" size="mini">申请</el-tag>
                  <el-tag v-if="form.status==1" type="success" size="mini">认证</el-tag>
                  <el-tag v-if="form.status==2" type="danger" size="mini">注销</el-tag>
                </el-descriptions-item>
              </el-descriptions>
              <el-descriptions title="认证信息" :column="1" v-if="form.status==1">
                <el-descriptions-item label="认证日期">{{ form.approvalDate }}</el-descriptions-item>
                <el-descriptions-item label="认证人员">{{ form.approvalBy }}</el-descriptions-item>
<!--                <el-descriptions-item label="认证说明">{{ form.approvalInfo }}</el-descriptions-item>-->
              </el-descriptions>
              <el-descriptions title="注销信息" :column="1" v-if="form.status==2">
                <el-descriptions-item label="注销日期">{{ form.revocationDate }}</el-descriptions-item>
                <el-descriptions-item label="注销人员">{{ form.revocationBy }}</el-descriptions-item>
                <el-descriptions-item label="注销原因">{{ form.revocationInfo }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div style="width: 50%;float: right">
              <el-descriptions title="防伪码" :colon="false" :column="1">
                <el-descriptions-item>
                  <el-input type="textarea" :rows="4" readonly v-model="form.securityCode"/>
                </el-descriptions-item>
              </el-descriptions>
              <el-descriptions style="margin-top: 10px" title="二维码" :colon="false" :column="1">
                <el-descriptions-item>
                  <el-image style="width: 300px; height: 300px" :src="form.qrCode" fit="cover"/>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="证书" name="second">
          <div>
            <center>
                <el-image style="width: 60%;height: 80%;border:2px solid #F1F1F1" :src="form.certImg" fit="fill" :preview-src-list="srcList"/>
            </center>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>


</template>

<script>
import {listCert, getCert, delCert, addCert, updateCert} from "@/api/cert/cert";
import {listTraining_class} from "@/api/pv/training_class";
import {listUser_simple} from "@/api/system/userStudent";
import {listCert_organization, getCert_organization} from "@/api/cert/cert_organization";
import {listCert_type} from "@/api/cert/cert_type";
import class_score from "@/views/pv/class_score/index.vue";
function isEmpty(obj){
  return obj == undefined || obj == null || obj == '';
}
export default {
  name: "Cert",
  computed: {
    class_score() {
      return class_score
    }
  },
  data() {
    return {
      active3: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书表格数据
      certList: [],
      // 班级数据
      training_classList: [],
      // 机构数据
      cert_organizationList: [],
      cert_TypeList: [],
      srcList:[],
      // 学生数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cancellati: false,
      approval: false,
      dialogTableVisible: false,
      // 预留字段2时间范围
      daterangeIssuanceDate: [],
      // 步骤条初始值
      active: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certNo: null,
        name: null,
        issuanceDate: null,
        certOrganizationId: null,
        classId: null,
        studentId: null,
        certTypeId: null,
        deptId: null,
        status: null,
        approvalDate: null,
        approvalBy: null,
        approvalInfo: null,
        revocationDate: null,
        revocationBy: null,
        revocationInfo: null,
        securityCode: null,
        qrCode: null,
        certImg: null,
        reservedOne: null,
        reservedTwo: null,
        startTime: null,
        endTime: null,
        certOrganization: {name: null},
        student: {name: null},
        studentIds:[],
        params:{

        }
      },
      // 表单参数
      form: {
        certOrganization: {name: null},
        student: {name: null},
        createTime:null,
      },
      forms: {},
      // 表单校验
      rules: {},
      studentLists: ''
    };
  },
  created() {
    this.getClassList();
    this.getOrganizationList();
    this.getCertTypeListList();
    this.getList();
  },
  methods: {
    // 格式化日期的函数
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    certNodeatil(id) {
      getCert(id).then(response => {
        this.form = response.data;
        this.dialogTableVisible = true;
        this.title = "证书信息";
      });
    },
    /** 查询学员管理列表 */
    getStuList() {
      this.studentList = [];
      listUser_simple().then(response => {
        response.rows.forEach(item => {
          this.studentList.push({
            key: item.userId,
            label: item.nickName,
            disabled: item.avatar == null || item.avatar==''
          });
        })
      });
    },
    filterMethod(query, item) {
      return item.label.indexOf(query) > -1;
    },

    /** 查询证书列表 */
    getList() {
      this.loading = true;
      this.queryParams.params['beginIssuanceDate'] = null;
      this.queryParams.params['endIssuanceDate'] = null;
      if (null != this.daterangeIssuanceDate && '' != this.daterangeIssuanceDate) {
        this.queryParams.params["beginIssuanceDate"] = this.daterangeIssuanceDate[0];
        this.queryParams.params["endIssuanceDate"] = this.daterangeIssuanceDate[1];
      }
      if (null != this.queryParams.startTime){
        // 从startTime中提取年份
        const year = new Date(this.queryParams.startTime).getFullYear();
        // 创建该年份最后一天的Date对象（12月31日 23:59:59）
        const endDate = new Date(year, 11, 31, 23, 59, 59);
        // 格式化为YYYY-MM-DD HH:mm:ss
        const padZero = num => num.toString().padStart(2, '0');
        const formattedDate =
          `${endDate.getFullYear()}-${padZero(endDate.getMonth() + 1)}-${padZero(endDate.getDate())} ` +
          `${padZero(endDate.getHours())}:${padZero(endDate.getMinutes())}:${padZero(endDate.getSeconds())}`;
        // 赋值给endTime
        this.queryParams.endTime = formattedDate;
      }else {
        this.queryParams.endTime = '';
      }
      listCert(this.queryParams).then(response => {
        this.certList = response.rows;
        this.srcList = this.certList.map(cert => cert.certImg);
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询颁发类型列表 */
    getCertTypeListList() {
      listCert_type({pageSize: 1000, pageNum: 1}).then(response => {
        this.cert_TypeList = response.rows;
      });
    },

    /** 查询颁发机构列表 */
    getOrganizationList() {
      listCert_organization({pageSize: 1000, pageNum: 1}).then(response => {
        this.cert_organizationList = response.rows;
      });
    },
    /** 查询培训班管理列表 */
    getClassList() {
      listTraining_class({pageSize: 1000, pageNum: 1}).then(response => {
        this.training_classList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.approval = false;
      this.cancellati = false;
      this.active = 0;
      this.reset();
      this.forms = {};
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        certNo: null,
        name: null,
        issuanceDate: null,
        certOrganizationId: null,
        classId: null,
        studentId: null,
        certTypeId: null,
        deptId: null,
        status: null,
        approvalDate: null,
        approvalBy: null,
        approvalInfo: null,
        revocationDate: null,
        revocationBy: null,
        revocationInfo: null,
        securityCode: null,
        qrCode: null,
        certImg: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        reservedOne: null,
        reservedTwo: null,
        certOrganization: {name: null},
        student: {name: null},
        studentIds:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.startTime = null;
      this.queryParams.userName = null;
      this.daterangeIssuanceDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加证书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCert(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改证书";
      });
    },
    /** 认证操作 */
    approvalOpen(row) {
      this.reset();
      this.form = {...row};
      this.form.status = 1;
      this.approval = true;
      this.title = "认证证书";
    },
    /** 注销操作 */
    cancellatiOpen(row) {
      this.reset();
      this.form = {...row};
      this.form.status = 2;
      this.cancellati = true;
      this.title = "注销证书";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCert(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.getList();
            });
          } else {
            addCert(this.forms).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    submitForms() {
      const loading = this.$loading({
        lock: true,
        text: '后台正在审核，请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$refs["forms"].validate(valid => {
        if (valid) {
          addCert(this.forms).then(response => {
            loading.close();
            this.$modal.msgSuccess("新增成功");
            this.cancel();
            this.getList();
            this.active = 0;
          });
        }

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除证书编号为"' + row.certNo + '"的数据项？').then(function () {
        return delCert(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 复选框选中数据 */
    handleCertOrganizationSelectionChange(selection) {
      this.checkedCertOrganization = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.queryParams.startTime) {
        const year = new Date(this.queryParams.startTime).getFullYear();
        const endDate = new Date(year, 11, 31, 23, 59, 59);
        const padZero = num => num.toString().padStart(2, '0');
        const formattedDate =
          `${endDate.getFullYear()}-${padZero(endDate.getMonth() + 1)}-${padZero(endDate.getDate())} ` +
          `${padZero(endDate.getHours())}:${padZero(endDate.getMinutes())}:${padZero(endDate.getSeconds())}`;
        this.queryParams.endTime = formattedDate;
      } else {
        this.queryParams.endTime = '';
      }
      const now = new Date();
      const formattedDate = this.formatDate(now);

      // 调用下载方法，设置超时（例如60秒）
      this.download(
        'cert/cert/export',
        { ...this.queryParams },
        `证书列表_${formattedDate}.xlsx`,
        60000 // 超时时间（60,000毫秒 = 60秒）
      );
    },
    /**下一步按钮 */
    next() {
      if (this.active == '0' && isEmpty(this.forms.classId)){
        this.$modal.msgWarning("请选择班级");
        return;
      }
      if (this.active == '1'){
        if (isEmpty(this.forms.certOrganizationId)){
          this.$modal.msgWarning("请选择颁证机构");
          return;
        }
        if (isEmpty(this.forms.issuanceDate)){
          this.$modal.msgWarning("请选择颁发日期");
          return;
        }
      }
      if (this.active == '3' && isEmpty(this.forms.classId)){
        this.$modal.msgWarning("请选择班级");
        return;
      }
      if (this.active == '3' && (isEmpty(this.forms.studentIds) || this.forms.studentIds.length <= 0)){
        this.$modal.msgWarning("请选择人员");
        return;
      }
      if (this.active++ > 3) this.active = 0;
      if (this.active == 2) {
        getCert_organization(this.forms.certOrganizationId).then(response => {
          this.forms.name = response.data.name;
        });
      }
    },
    /**上一步按钮 */
    back() {
      if (this.active-- < 3) this.active = 0;
    },
    //表格字体颜色
    tableRowClassName({row, rowIndex}) {
      return (row.status === 0) ? 'approved' : (row.status === 1) ? 'attestation' : (row.status === 2) ? 'deactive' : '';
    }
  },
  //监听器
  watch: {
    'open': function (n, o) {
      this.active = 0;
    }
  }
};
</script>
<style>
.el-table .approved {
  color: rgb(239, 68, 68);
}
.el-table .attestation {
  color: rgb(34, 197, 94);
}
.el-table .deactive {
  color: rgb(113, 113, 122);
  text-decoration: line-through
}
</style>
